package hcd.electrick;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by david on 2017/1/31.
 */
public class LoginFragment extends Fragment {

    private EditText usernameText;
    private EditText passwordText;
    private EditText verifyText;
    private ImageButton verifyImg;
    private Button loginBtn;

    private VerifyImgHandler verifyImgHandler;
    private LoginFinishHandler loginFinishHandler;

    private String verifySession;

    private ProgressDialog loadingIndicator;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getActivity().setTitle("登陆");
        ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        View rootView = inflater.inflate(R.layout.fragment_login, container, false);

        usernameText = (EditText) rootView.findViewById(R.id.usernameText);
        passwordText = (EditText) rootView.findViewById(R.id.passwordText);
        verifyText = (EditText) rootView.findViewById(R.id.verifyText);
        verifyImg = (ImageButton) rootView.findViewById(R.id.verifyImg);
        loginBtn = (Button) rootView.findViewById(R.id.loginBtn);

        verifyImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getVerifyImg();
            }
        });

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goLogin();
            }
        });

        verifyImgHandler = new VerifyImgHandler();
        loginFinishHandler = new LoginFinishHandler();

        getVerifyImg();

        loadingIndicator = new ProgressDialog(getContext(), ProgressDialog.STYLE_SPINNER);
        loadingIndicator.setMessage("请稍后");

        SharedPreferences preferences = getContext().getSharedPreferences("user", Context.MODE_PRIVATE);
        Log.d("preference", preferences.getString("username", "null")+", "+preferences.getString("psw", "null"));

        String username = preferences.getString("username", null);
        if (username != null){
            usernameText.setText(username);
            String psw = preferences.getString("psw", null);
            if (psw != null){
                passwordText.setText(psw);
                verifyText.requestFocus();
            }else {
                passwordText.requestFocus();
            }
        }
        return rootView;
    }



    // 获取验证码图片
    private void getVerifyImg(){

        new Thread(){
            @Override
            public void run() {
                super.run();
                String urlStr = getString(R.string.domain_name) + "/getECard.php";
                try{
                    URL url = new URL(urlStr);

                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    if (connection.getResponseCode() == 200) {
                        Log.d("cookie", connection.getHeaderField("Set-Cookie"));
                        verifySession = connection.getHeaderField("Set-Cookie");
                        Bitmap bm = BitmapFactory.decodeStream(connection.getInputStream());
                        verifyImgHandler.obtainMessage(0, bm).sendToTarget();
                    }

//                    Bitmap bm = BitmapFactory.decodeStream(url.openStream());
//
//                    verifyImgHandler.obtainMessage(0, bm).sendToTarget();
                }catch (Exception err) {
                    err.printStackTrace();
                }
            }
        }.start();

    }

    //登陆
    private void goLogin(){
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(verifyText.getWindowToken(), 0);
        if (checkInput()){
            setPostState(true);
            new Thread(){
                @Override
                public void run() {
                    super.run();

                    String username = usernameText.getText().toString();
                    String password = passwordText.getText().toString();
                    String verify = verifyText.getText().toString();
                    String param = "uname="+username+"&psw="+password+"&verify="+verify;
                    Log.d("ok, post", param);
                    try{
                        URL url = new URL(getString(R.string.domain_name) + "/ec.php");
//                        URL url = new URL("http://hcdstudio.cn/post.php");
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setRequestMethod("POST");
                        connection.setRequestProperty("Cookie", verifySession);
                        connection.setDoInput(true);
                        connection.setDoOutput(true);
                        PrintWriter pw = new PrintWriter(connection.getOutputStream());
                        pw.print(param);
//                        pw.print("text=sadf");
                        pw.flush();
                        connection.connect();
                        String result = "";
                        if (connection.getResponseCode() == 200) {
                            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                            String line;
                            while ((line = reader.readLine()) != null) {
                                result += line;
                            }
                            Log.d("result", result);
                            String[] data = result.split("\\|");
//                            for (String aData : data) Log.d("println", aData);
                            if (data.length > 1){
                                loginFinishHandler.obtainMessage(0, data).sendToTarget();
                            }else {
                                loginFinishHandler.obtainMessage(1, null).sendToTarget();
                            }
                            reader.close();


                        }else{
                            throw new Exception("网络错误");
                        }


                        pw.close();
                        connection.disconnect();
                    }catch (Exception err) {
                        loginFinishHandler.obtainMessage(1, null).sendToTarget();
                        err.printStackTrace();
                    }

                }
            }.start();

        }
    }

    // 检查是否符合上传要求
    private boolean checkInput(){
        String username = usernameText.getText().toString();

        if (username.length() < 8) {
            Toast.makeText(this.getContext(), getString(R.string.username)+getString(R.string.invalid), Toast.LENGTH_SHORT).show();
            usernameText.requestFocus();
            return false;
        }

        String password = passwordText.getText().toString();
        if (password.length() < 6) {
            Toast.makeText(this.getContext(), getString(R.string.password)+getString(R.string.not_enough_length), Toast.LENGTH_SHORT).show();
            passwordText.requestFocus();
            return false;
        }

        String verify = verifyText.getText().toString();
        if (verify.length() < 4) {
            Toast.makeText(this.getContext(), getString(R.string.verify)+getString(R.string.not_enough_length), Toast.LENGTH_SHORT).show();
            verifyText.requestFocus();
            return false;
        }

        return true;
    }

    @SuppressLint("HandlerLeak")
    private class VerifyImgHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == 0) {
                Bitmap bm = (Bitmap) msg.obj;
                verifyImg.setImageBitmap(bm);
            }
        }
    }

    @SuppressLint("HandlerLeak")
    private class LoginFinishHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            setPostState(false);
            if (msg.what == 0){
                String[] list = (String[]) msg.obj;
                Log.d("handler", "readyTran");

                SharedPreferences.Editor preferences = getContext().getSharedPreferences("user", Context.MODE_PRIVATE).edit();
                preferences.putString("username", usernameText.getText().toString());
                preferences.putString("psw", passwordText.getText().toString());
                preferences.apply();

                BalanceFragment fragment = new BalanceFragment();
                Bundle data = new Bundle();
                data.putStringArray("value", list);
                data.putString("session", verifySession);
                fragment.setArguments(data);

                getActivity().getSupportFragmentManager().beginTransaction()
                        .replace(R.id.container, fragment)
                        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                        .commit();
            }else {
                Toast.makeText(getContext(), "登陆失败,请检查用户名、密码、和验证码是否正确", Toast.LENGTH_SHORT).show();
                getVerifyImg();
            }
        }
    }

    private void setPostState(boolean state){
        verifyImg.setEnabled(!state);
        loginBtn.setEnabled(!state);
        if (state){
            loadingIndicator.show();
        }else {
            loadingIndicator.hide();
        }
    }
}
